package pers.qianyu.auth.security.service;

import org.springframework.beans.factory.annotation.*;
import org.springframework.security.core.*;
import org.springframework.security.core.userdetails.*;
import org.springframework.stereotype.*;
import pers.qianyu.auth.pojo.entity.*;
import pers.qianyu.auth.security.model.*;
import pers.qianyu.auth.service.*;

import java.util.*;
import java.util.stream.*;

@Service
public class UserDetailsServiceImpl implements UserDetailsService {
    @Autowired
    private UserService userService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        UserPO userPO = userService.findByUsername(username);
        if (Objects.isNull(userPO)) {
            throw new UsernameNotFoundException("该用户不存在");
        }
        List<String> permissions = userPO.getRoles().stream()
                .flatMap(role -> role.getAuthorities().stream())
                .map(AuthorityPO::getName)
                .collect(Collectors.toList());
        List<GrantedAuthority> grantedAuthorities = permissions.stream()
                .map(GrantedAuthorityImpl::new)
                .collect(Collectors.toList());
        return new User(userPO.getUsername(), userPO.getPassword(), grantedAuthorities);
    }
}